package cn.bdqn.tets;


import cn.bdqn.entity.Person;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class HibernateTest {
    Session session;
    SessionFactory sf;
    Transaction tx;
    @Before
    public  void init(){
        //读取配置文件
        Configuration cfg=new Configuration();
        //默认去加载核心配置文件hibernate.cfg.xml
        cfg.configure();
        //创建sessionFactoryg工厂
         sf=cfg.buildSessionFactory();
        //创建员工
         session=sf.openSession();
        //先开启事物
         tx=session.beginTransaction();
    }
    @Test
    public void findOne(){

        //查询一行数据 根据id查询
        Person person =session.get(Person.class,1);
        System.out.println(person);
    }
    @Test
    public void  addPerson(){
         Person person=new Person();
         person.setName("李四");

        session.save(person);

    }
    @Test
    public void  updateperson(){
         //更新：先查出来 ，在进行秀海
        Person person=session.get(Person.class,2);

        person.setName("12");
        session.update(person);
    }
    @Test
    public void delperson(){
        Person person=new Person();
        person.setId(1);

        session.delete(person);
    }
    @Test
    public void finAll(){
        //查询全部
        //HQL hibernate query languan
        //在HQL里不能出现任何表明字段名
        Query query =session.createQuery("from Person");
        List<Person> list =query.list();
        for (Person person:list){
            System.out.println(person);
        }
    }
    @Test
    public void Test(){

    }
    @After
    public void after(){
        //提交事务
        tx.commit();
        //释放资源
        session.close();
        sf.close();
    }
}
